﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
using Viettel.VOFFICE.DAO.Models;
using Viettel.VOFFICE.Web.Helpers;
using Viettel.VOFFICE.Web.Models;
using Viettel.VOFFICE.util;

namespace Viettel.VOFFICE.Web.Controllers
{
    public class MetaDataController : BaseController
    {



        [HttpGet]
        [ActionName("get_all_meta")]
        public JsonResult GetAllMeta(int pageSize = 0, int pageIndex = 0)
        {
            if (pageSize <= 0 && pageIndex == 0)
            {
                try
                {
                    var item = unitOfWork.MetaDataRepository.Get();
                    return Json(new JsonResponse()
                    {
                        Status = true,
                        Result = item.Select(o => new MetaDataModel(o)).ToList()
                    }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                    return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                try
                {
                    var item = unitOfWork.MetaDataRepository.GetPaging(pageSize, pageIndex);
                    return Json(
                        new JsonResponse()
                        {
                            Status = true,
                            Result = new
                            {
                                pageSize = item.PageSize,
                                pageIndex = item.PageIndex,
                                PageCount = item.PageCount,
                                Item = item.Select(o => new MetaDataModel(o)).ToList()
                            }
                        }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                    return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
                }
            }
        }

        [HttpPut]
        [ActionName("update_metadata")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult UpdateMetaData(MetaDataModel metaData, string modified= "all")
        {
            try
            {
                List<ValidationResult> outError;
                if (metaData.IsValid(out  outError))
                {
                    var data = unitOfWork.MetaDataRepository.GetById(metaData.Id);
                    if (data == null)
                    {
                        return Json(new JsonResponse()
                                        {
                                            Status = false,
                                            Result = "không cập nhật mới được"
                                        });
                    }
                    if (modified.ToUpper().Contains("ISACTIVE"))
                    {
                        data.IsActive = metaData.IsActive;
                    }

                    else
                    {
                        data.Name = metaData.Name;
                        data.Type = metaData.Type;
                        data.IsActive = metaData.IsActive;
                        data.ParentId = metaData.ParentId;
                        data.CreatorId = metaData.CreatorId;
                    }
                    data.UpdatedAt = DateTime.Now;
                    data.CreatedAt = DateTime.Now;
                    unitOfWork.MetaDataRepository.Update(data);
                    return Json(SimplyResponse.Response200());
                }
                else
                {
                    return Json(new JsonResponse()
                    {
                        Status = false,
                        Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                    });
                }
            }
            catch (Exception)
            {
                
                return Json(SimplyResponse.Response200());
            }
        }
        [HttpPost]
        [ActionName("add_metadata")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult AddMetadata(MetaDataModel metaData)
        {
            try
            {
                try
                {
                    List<ValidationResult> outError;
                    if (!metaData.IsValid(out outError))
                    {
                        return Json(new JsonResponse()
                                        {
                                            Status = false,
                                            Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                                        });
                    } //end ìf
                    else
                    {
                        var data = new MetaData()
                                       {
                                           //Id = metaData.Id,
                                           Name = metaData.Name,
                                           Type = metaData.Type,
                                           ParentId = metaData.ParentId,
                                           IsActive = metaData.IsActive,
                                           CreatedAt = DateTime.Now,
                                           UpdatedAt = DateTime.Now,
                                       };
                        unitOfWork.MetaDataRepository.Insert(data);
                        return Json(SimplyResponse.ResposeWithId(data.Id));
                    }
                }
                catch (Exception)
                {
                    return Json(SimplyResponse.Response500());
                    //throw;
                }
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                //throw;
            }
        }
        //chạy tốt
        [HttpPost]
        [ActionName("delete_metadata")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult DeleteMetaData(int id)
        {
            try
            {
                unitOfWork.MetaDataRepository.Delete(id);
                return Json(SimplyResponse.Response200());
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                //throw;
            }
        }

        //[HttpGet]
        //[ActionName("search_metadata")]
        //public JsonResult SearchMetadata(string key)
        //{
        //    try
        //    {
        //        var items = unitOfWork.MetaDataRepository.Search(key);
        //        return Json(new JsonResponse() { Status = true, Result = items.Select(o => new BookModel(o)) },
        //                    JsonRequestBehavior.AllowGet);
        //                    JsonRequestBehavior.AllowGet);
        //                    JsonRequestBehavior.AllowGet);
        //                    JsonRequestBehavior.AllowGet);
        //                    JsonRequestBehavior.AllowGet);
        //    }
        //    catch (Exception)
        //    {
        //        return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
        //        //throw;
        //    }
        //}
    }
}
